package com.adgox.tiantianbiting.mine.index;


import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityOptions;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.adgox.tiantianbiting.R;
import com.adgox.tiantianbiting.base.BasicFragment;
import com.adgox.tiantianbiting.bean.BaseResponseBean;
import com.adgox.tiantianbiting.bean.MessageCountBean;
import com.adgox.tiantianbiting.bean.UserInfo;
import com.adgox.tiantianbiting.home.programDetail.ProgramDetailActivity;
import com.adgox.tiantianbiting.mine.help.HelpActivity;
import com.adgox.tiantianbiting.mine.login.LoginActivity;
import com.adgox.tiantianbiting.mine.message.MessageActivity;
import com.adgox.tiantianbiting.mine.mobile.BindMobileActivity;
import com.adgox.tiantianbiting.mine.wallet.MyWalletActivity;
import com.adgox.tiantianbiting.music.MusicService;
import com.adgox.tiantianbiting.net.callback.JsonCallback;
import com.adgox.tiantianbiting.utils.ApiConstant;
import com.adgox.tiantianbiting.utils.DialogUtils;
import com.adgox.tiantianbiting.utils.SpUtils;
import com.bumptech.glide.Glide;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.makeramen.roundedimageview.RoundedImageView;
import com.rae.swift.session.SessionManager;

import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

public class MineFragment extends BasicFragment {

    Unbinder unbinder;
    @BindView(R.id.img_avatar)
    RoundedImageView imgAvatar;
    @BindView(R.id.tv_username)
    TextView tvUsername;
    @BindView(R.id.textView2)
    TextView textView2;
    @BindView(R.id.imageView)
    ImageView imageViewmsg;
    @BindView(R.id.msg_unread)
    ImageView msg_unread;
    @BindView(R.id.fl_logout)
    FrameLayout flLogout;

    private static final String MSG_COUNT = "MSG_COUNT";
    private static final String SYSTEM_MSG = "systemmsg";
    private static final String ACTIVITY_MSG = "activitymsg";

    public static MineFragment newInstance() {
        return new MineFragment();
    }

    @Override
    public int getLayoutId(Bundle var1) {
        return R.layout.fragment_mine;
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onResume() {
        super.onResume();
        initView();
        checkNesMsg();
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            checkNesMsg();
            checkIsLogin();
        }
    }

    private void initView() {
        UserInfo userInfo = SessionManager.getDefault().getUser();
        int userId = userInfo == null ? 0 : userInfo.getId();
        if (userId != 0) {
            flLogout.setVisibility(View.VISIBLE);
            OkGo.<BaseResponseBean<UserInfo>>get(ApiConstant.BASE_URL + ApiConstant.GET_USERINFO)
                    .params("userId", userId)
                    .execute(new JsonCallback<BaseResponseBean<UserInfo>>() {
                        @Override
                        public void onSuccess(Response<BaseResponseBean<UserInfo>> response) {
                            UserInfo userInfo = response.body().getData();
                            setUserInfo(userInfo);
                        }
                    });
        } else {
            imgAvatar.setImageResource(R.drawable.ic_avatar);
            tvUsername.setText("点击登录");
            flLogout.setVisibility(View.GONE);
        }
    }

    private void  checkIsLogin(){
        UserInfo userInfo = SessionManager.getDefault().getUser();
        int userId = userInfo == null ? 0 : userInfo.getId();
        if (userId==0){
            textView2.setVisibility(View.GONE);
            imageViewmsg.setVisibility(View.GONE);
            msg_unread.setVisibility(View.GONE);
        }else{
            textView2.setVisibility(View.VISIBLE);
            imageViewmsg.setVisibility(View.VISIBLE);
        }
    }
    private void checkNesMsg() {
        UserInfo userInfo = SessionManager.getDefault().getUser();
        int userId = userInfo == null ? 0 : userInfo.getId();
        if(userId==0)return;
        String msg_count = SpUtils.getString(getContext(), "MSG_COUNT");
        if (TextUtils.isEmpty(msg_count)) {
            OkGo.<BaseResponseBean<MessageCountBean.DataBean>>get(ApiConstant.BASE_URL + ApiConstant.MY_MESSAGE_UNREAD_LIST)
                    .params("userId", userId)
                    .params("type", "3")
                    .execute(new JsonCallback<BaseResponseBean<MessageCountBean.DataBean>>() {
                        @Override
                        public void onSuccess(Response<BaseResponseBean<MessageCountBean.DataBean>> response) {
                            DialogUtils.dismiss();
                            msg_unread.setVisibility(response.body().getData().getSysMsg() > 0 ? View.VISIBLE : View.GONE);
                        }

                        @Override
                        public void onError(Response<BaseResponseBean<MessageCountBean.DataBean>> response) {
                            super.onError(response);
                            DialogUtils.dismiss();
                        }
                    });
        } else {

            if (TextUtils.isEmpty(SpUtils.getString(getContext(),ACTIVITY_MSG))|| TextUtils.isEmpty(SpUtils.getString(getContext(),SYSTEM_MSG))){
                OkGo.<BaseResponseBean<MessageCountBean.DataBean>>get(ApiConstant.BASE_URL + ApiConstant.MY_MESSAGE_UNREAD_LIST)
                        .params("userId", userId)
                        .params("type", "3")
                        .execute(new JsonCallback<BaseResponseBean<MessageCountBean.DataBean>>() {
                            @Override
                            public void onSuccess(Response<BaseResponseBean<MessageCountBean.DataBean>> response) {
                                DialogUtils.dismiss();
                                msg_unread.setVisibility(response.body().getData().getSysMsg() > 0 ? View.VISIBLE : View.GONE);
                            }

                            @Override
                            public void onError(Response<BaseResponseBean<MessageCountBean.DataBean>> response) {
                                super.onError(response);
                                DialogUtils.dismiss();
                            }
                        });
            }else{
                OkGo.<BaseResponseBean<MessageCountBean.DataBean>>get(ApiConstant.BASE_URL + ApiConstant.MY_MESSAGE_UNREAD_LIST)
                        .params("userId", userId)
                        .params("type", "3")
                        .params("startTime", msg_count)
                        .execute(new JsonCallback<BaseResponseBean<MessageCountBean.DataBean>>() {
                            @Override
                            public void onSuccess(Response<BaseResponseBean<MessageCountBean.DataBean>> response) {
                                DialogUtils.dismiss();
                                msg_unread.setVisibility(response.body().getData().getSysMsg() > 0 ? View.VISIBLE : View.GONE);
                            }

                            @Override
                            public void onError(Response<BaseResponseBean<MessageCountBean.DataBean>> response) {
                                super.onError(response);
                                DialogUtils.dismiss();
                            }
                        });
            }
            }


    }

    private void setUserInfo(UserInfo userInfo) {
        SessionManager.getDefault().setUser(userInfo);
        Glide.with(getContext()).load(userInfo.getWxAvatarUrl()).into(imgAvatar);
        tvUsername.setText(userInfo.getWxNickname());
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick(R.id.fl_wallet)
    public void onWalletClicked() {
        if (!SessionManager.getDefault().isLogin()) {
            startActivity(new Intent(getActivity(), LoginActivity.class));
            return;
        }
        Intent intent = new Intent(getActivity(), MyWalletActivity.class);
        startActivity(intent);
    }

    @OnClick({R.id.img_avatar, R.id.tv_username})
    public void onLoginClicked(View view) {
        if (!SessionManager.getDefault().isLogin()) {
            startActivity(new Intent(getActivity(), LoginActivity.class));
        }
    }

    @OnClick(R.id.fl_logout)
    public void onLogoutClicked() {
        SessionManager.getDefault().clear();
        initView();
        //有后台播放就杀死
        ActivityManager am = (ActivityManager) getActivity().getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo> runningServices = am.getRunningServices(Integer.MAX_VALUE);
        for (ActivityManager.RunningServiceInfo info : runningServices) {
            if (info.service.getClassName().equals("com.adgox.tiantianbiting.music.MusicService")) {
                Intent intentService = new Intent(getActivity(), MusicService.class);
                intentService.putExtra("option", "kill");
                getActivity().startService(intentService);
            }
        }
    }

    @OnClick({R.id.imageView, R.id.textView2,R.id.view2})
    public void onMessageClick() {
        startActivity(new Intent(getContext(), MessageActivity.class));
    }

    @OnClick(R.id.fl_download)
    public void onDownloadClicked() {
        if (!SessionManager.getDefault().isLogin()) {
            startActivity(new Intent(getActivity(), LoginActivity.class));
            return;
        }
        startActivity(new Intent(getActivity(), BindMobileActivity.class));
    }

    @OnClick(R.id.fl_help)
    public void onHelpClicked() {
        if (!SessionManager.getDefault().isLogin()) {
            startActivity(new Intent(getActivity(), LoginActivity.class));
            return;
        }
        startActivity(new Intent(getActivity(), HelpActivity.class));
    }
}
